package Jun13.doc;

import Jun13.pojo.User;
import Jun13.utils.ESUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class InsertDoc {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient rest = ESUtils.getRest();//获取ES对象
        IndexRequest index = new IndexRequest().index("user").id("1001");//通过IndexRequest指定在哪个索引下创建文档对象，id是多少
        ObjectMapper om = new ObjectMapper();//创建ObjectMapper对象
        String json = om.writeValueAsString(new User("刘晁铭", 23, "男"));//将数据写成json
        index.source(json, XContentType.JSON);//将json添加进IndexRequest，后续发送就可以添加数据
        IndexResponse result = rest.index(index, RequestOptions.DEFAULT);//发送添加数据请求
        System.out.println(result.getResult());//打印结果
        rest.close();//关闭
    }
}
